package com.wh.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test6 {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        //获取Class对象
        Class c=User.class;

        //构造一个对象
        User user = (User) c.newInstance();//本质是调用无参构造
        System.out.println(user);

        //使用有参构造
        Constructor constructor = c.getConstructor(String.class, Integer.class);
        User user2 = (User)constructor.newInstance("lwc", 18);
        System.out.println(user2);

        //通过反射调用方法
        User user3 = (User)c.newInstance();
        Method setName = c.getMethod("setName", String.class);
        setName.invoke(user3,"王欢");
        System.out.println(user3);

        //通过反射操作属性
        User user4= (User) c.newInstance();
        Field name = c.getDeclaredField("name");
        name.setAccessible(true);//关闭程序的安全检测才能操作私有属性
        name.set(user4,"李宛聪");
        System.out.println(user4);
    }
}
